package io.finer.erp.jeecg.bas.service.impl;

import io.finer.erp.jeecg.bas.entity.BasProductFormula;
import io.finer.erp.jeecg.bas.dto.FormulaDTO;
import io.finer.erp.jeecg.bas.entity.BasPfMaterial;
import io.finer.erp.jeecg.bas.mapper.BasPfMaterialMapper;
import io.finer.erp.jeecg.bas.mapper.BasProductFormulaMapper;
import io.finer.erp.jeecg.bas.service.IBasProductFormulaService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 产品配方
 * @Author: jeecg-boot
 * @Date:   2020-10-19
 * @Version: V1.0
 */
@Service
public class BasProductFormulaServiceImpl extends ServiceImpl<BasProductFormulaMapper, BasProductFormula> implements IBasProductFormulaService {

	@Autowired
	private BasProductFormulaMapper basProductFormulaMapper;
	@Autowired
	private BasPfMaterialMapper basPfMaterialMapper;
	
	@Override
	@Transactional
	public void saveMain(BasProductFormula basProductFormula, List<BasPfMaterial> basPfMaterialList) {
		basProductFormulaMapper.insert(basProductFormula);
		if(basPfMaterialList!=null && basPfMaterialList.size()>0) {
			for(BasPfMaterial entity:basPfMaterialList) {
				//外键设置
				entity.setPfid(basProductFormula.getId());
				basPfMaterialMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(BasProductFormula basProductFormula,List<BasPfMaterial> basPfMaterialList) {
		basProductFormulaMapper.updateById(basProductFormula);
		
		//1.先删除子表数据
		basPfMaterialMapper.deleteByMainId(basProductFormula.getId());
		
		//2.子表数据重新插入
		if(basPfMaterialList!=null && basPfMaterialList.size()>0) {
			for(BasPfMaterial entity:basPfMaterialList) {
				//外键设置
				entity.setPfid(basProductFormula.getId());
				basPfMaterialMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		basPfMaterialMapper.deleteByMainId(id);
		basProductFormulaMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			basPfMaterialMapper.deleteByMainId(id.toString());
			basProductFormulaMapper.deleteById(id);
		}
	}

	@Override
	public List<FormulaDTO> getFormulaByCategoryId(String categoryId) {
		return this.baseMapper.getFormulaByCategoryId(categoryId);
	}

	@Override
	public Result<?> getFormulaByCategory(String categoryId) {
		List<FormulaDTO> list = this.getFormulaByCategoryId(categoryId);
		return Result.ok(list);
	}
	
}
